package com.stone.framework.batch.job;

import javax.sql.DataSource;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;

import com.stone.framework.batch.model.CaseAllocBO;
import com.stone.framework.batch.service.CaseService;
import com.stone.framework.batch.partitioner.DefaultPartitioner;
import com.stone.framework.batch.writer.ItemBatchWriterAdapter;

@Configuration
public class StraFirstResultUpdatingJob {

	@Autowired
	private JobBuilderFactory jobBuilderFactory;

	@Autowired
	private StepBuilderFactory stepBuilderFactory;

	@Autowired
	private DataSource dataSource;

	@Autowired
	private TaskExecutor taskExecutor;

	@Value("stone.batch.chunkSize:1000")
	private int chunkSize;

	@Value("stone.batch.threadSize:10")
	private int threadSize;

	@Autowired
	@Qualifier("batchedCaseService")
	private CaseService caseService;

	@Bean("job_straFirstResultUpdating")
	public Job job() {
		return jobBuilderFactory.get("job_straFirstResultUpdating").start(step()).build();
	}

	@Bean("step_straFirstResultUpdating")
	public Step step() {
		DefaultPartitioner partitioner = new DefaultPartitioner();
		return stepBuilderFactory.get("step_straFirstResultUpdating")
				.partitioner("step_straFirstResultUpdating_sub", partitioner).step(stepSub()).gridSize(threadSize)
				.taskExecutor(taskExecutor).build();
	}

	@Bean("step_straFirstResultUpdating_sub")
	public Step stepSub() {
		return stepBuilderFactory.get("step_straFirstResultUpdating_sub").<Object, CaseAllocBO>chunk(chunkSize)
				.reader(reader()).writer(writer()).build();
	}

	@Bean("reader_straFirstResultUpdating")
	public JdbcCursorItemReader<Object> reader() {
		return null;
	}

	@Bean("writer_straFirstResultUpdating")
	public ItemBatchWriterAdapter<CaseAllocBO> writer() {
		ItemBatchWriterAdapter<CaseAllocBO> writerAdapter = new ItemBatchWriterAdapter<>();
		writerAdapter.setTargetObject(caseService);
		writerAdapter.setTargetMethod("allocate");
		return writerAdapter;
	}

}
